package jwt

import (
	"errors"
	"time"

	"github.com/golang-jwt/jwt"
)

type JWTClaims struct {
	jwt.StandardClaims
	UserID string `json:"TokenID"`
}

func genToken(c *JWTClaims, secret []byte) (string, error) {
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, c)
	str, err := token.SignedString(secret)
	if err != nil {
		return "", err
	}
	return str, nil
}

func (c *JWTClaims) MakeToken(expireTime int, secret []byte) (string, error) {
	c.IssuedAt = time.Now().Unix()
	c.ExpiresAt = time.Now().Add(time.Second * time.Duration(expireTime)).Unix()

	return genToken(c, secret)
}

func VerifyToken(tokenStr string, secret []byte) (*JWTClaims, error) {
	token, err := jwt.ParseWithClaims(tokenStr, &JWTClaims{}, func(t *jwt.Token) (interface{}, error) {
		return secret, nil
	})

	if err != nil {
		return nil, err
	}

	claim, ok := token.Claims.(*JWTClaims)

	if !ok {
		return nil, errors.New("parse token failed")
	}
	if err := token.Claims.Valid(); err != nil {
		return nil, err
	}
	return claim, nil
}

func RefreshToken(tokenStr string, secret []byte) (string, error) {
	claim, err := VerifyToken(tokenStr, secret)
	if err != nil {
		return "", err
	}
	claim.ExpiresAt = time.Now().Unix() + (claim.ExpiresAt - claim.IssuedAt)
	signedToken, err := genToken(claim, secret)
	if err != nil {
		return "", err
	}
	return signedToken, nil
}
